package com.apes.fn.fico.expense;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.Arith;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/***
 * 定义赋能费用单
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicUpdate
@DynamicInsert
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = Expense.CONST_TABLE_NAME)
public class Expense extends Model {
    public static final String CONST_TABLE_NAME = "fn_expense";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "费用单", padding = 8, prefix = "PF")
    @Comment("费用单号")
    private String id; //收入单号
//
//    @NotNull
//    @ManyToOne(fetch = FetchType.LAZY)
//    @JoinColumn(name = "contract_id", referencedColumnName = "id")
//    @Comment("合同编码")
//    private Contract contract;
//
//    @Column(name = "contract_id", length = 250)
//    @Comment("合同")
//    private String contract; //备注

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id")
    @Comment("公司编码(平台)")
    private PartyRole company; //公司


    @Comment("总计")
    @Column(name = "amt_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    private double amtTotal = 0; //总计

    @States(name = "单据状态", values = {
            @State(id = "create", name = "制单"),
            @State(id = "apply", name = "申请"),
            @State(id = "approve", name = "审核"),
            @State(id = "stop", name = "终止"),
            @State(id = "reversal", name = "冲红"),
            @State(id = "delete", name = "删除"),
            @State(id = "partialDeduction", name = "部分扣收"),
            @State(id = "deducted", name = "已扣收"),
    })
    @Column(name = "state", length = 36, nullable = false)
    private String state; //状态


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "approve_id", referencedColumnName = "id")
    @Comment("审核人")
    private PartyRole approveId; //审核人

    @Column(name = "approve_date")
    @Comment("审核日期")
    private Date approveDate; //审核日期

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "apply_id", referencedColumnName = "id")
    @Comment("申请人")
    private PartyRole applyId;

    @Column(name = "apply_date")
    @Comment("申请日期")
    private Date applyDate;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "check_id", referencedColumnName = "id")
    @Comment("对账人")
    private PartyRole checkId; //PartyRole

    @Column(name = "check_date")
    @Comment("对账日期")
    private Date checkDate; //对账日期

    @Column(name = "remark", length = 250)
    @Comment("备注")
    private String remark; //备注

    @OneToMany(mappedBy = "expense", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<ExpenseItem> expenseItems = new ArrayList(); //结算商品

    public List<ExpenseItem> getExpenseItems() {
        for (ExpenseItem item : expenseItems) {
            item.setExpense(this);
        }
        return expenseItems;
    }


    @Transient
    private String tenants;

    public String getTenants() {
        if (expenseItems.isEmpty()) return null;
        return expenseItems.stream().map(ExpenseItem::getCompany).filter(Objects::nonNull).map(PartyRole::getName).collect(Collectors.joining(";"));
    }

    @Transient
    private PartyRole _creator;

    @Transient
    public PartyRole get_creator() {
        if (this.getCreator() == null) return null;
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }

    public void computeAmt() {
        amtTotal = 0;
        amtTotal= Arith.round(expenseItems.stream().mapToDouble(ExpenseItem::getAmount).sum(),2);
    }


    /**
     * 检查是否全部扣收
     */
    public void checkDeduct() {
        long count = expenseItems.stream().filter(expenseItem -> expenseItem.getAmountDeducted() == expenseItem.getAmount()).count();
        if (count == expenseItems.size()) {
            state = "deducted";
        } else {
            state = "partialDeduction";
        }
    }

    //支援确认单生成费用单转OA时需要用到
    @Transient
    private String processInitiator;
    @Transient
    private String processInitiatingDepartment;
    @Transient
    private String processInitiatingPost;


}
